<?php

class BPWriter
{
    private $yaml;
    private $sections;

    protected function toString()
    {
        $string = '<backup date="' . time() .'" >'. PHP_EOL;
        foreach($this->sections as $section)
        {
            $string .= $section->getSection(). PHP_EOL;
        }
        $string .= '</backup>';
        return $string;
    }

    public function __construct()
    {
        $this->sections = array();
        $this->yaml = new YamlToBPTable();
        foreach($this->yaml->getTables() as $table)
        {
            $tables = Doctrine_Core::getTable($table->getName())->findAll();
            $section = new BPSection($table->getName());
            foreach($tables as $element)
            {
                $element = new BPElement($table->getFields(), $element);
                $section->insertBPElement($element);
            }
            $this->sections[] = $section;
        }
    }

    public function toFile()
    {
        $backupFilePath = sfConfig::get('sf_config_dir') . '/backup/data.xml';
        $file = fopen($backupFilePath, 'w+');
        if($file)
        {
            fwrite($file, $this->toString());
            fclose($file);
            return true;
        }
        return false;
    }

}